<template>
  <el-dialog
    draggable
    overflow
    :title="titleMap[mode]"
    v-model="visible"
    :width="900"
    destroy-on-close
    @closed="$emit('closed')"
  >
    <el-form :model="form" :rules="rules" ref="dialogForm" label-width="70px">
      <el-row justify="space-evenly">
        <el-col :span="6" style="border-right: 2px solid #ccc">
          <el-row>
            <el-col :span="24">
              <el-form-item label="单号" prop="code">
                <el-input v-model="form.code" disabled placeholder="自动生成"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="日期" prop="billdate">
                <el-date-picker
                  v-model="form.billdate"
                  type="date"
                  placeholder="选择单据日期"
                  :disabled-date="disabledDate"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="加工厂" prop="outfactory_id">
                <skAutoChoose
                  v-model="form.outfactory.name"
                  :params="[{ category_id: 111 }]"
                  :name="'factory'"
                  :assign="form"
                  :asKey="'outfactory_id'"
                >
                </skAutoChoose>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="工价" prop="price">
                <el-input v-model="form.price"> </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="米数" prop="quantity">
                <el-input v-model="form.quantity" disabled> </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="金额" prop="amount">
                <el-input v-model="form.amount" disabled> </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark"> </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="运输单" prop="remark">
                <skAutoChoose
                  v-model="form.car.code"
                  :name="'car'"
                  :assign="form"
                  @select="selectCar"
                >
                </skAutoChoose>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="运输商" prop="remark">
                <skAutoChoose
                  v-model="form.car.company.name"
                  :name="'factory'"
                  :asKey="'company_id'"
                  :assign="form.car"
                  :params="[{ category_id: 54 }]"
                >
                </skAutoChoose>
              </el-form-item>
            </el-col> </el-row
        ></el-col>
        <el-col :span="18">
          <el-row>
            <el-col :span="24">
              <sc-VxeTable
                :tablecode="'pro_outsourcing_delivery_yl'"
                :data="form.details"
                :gridEvts="gridEvtsyl"
                :gridOps="{ height: 300 }"
                ref="subbeyl"
              >
              </sc-VxeTable>
            </el-col>
            <el-col :span="24">
              <sc-VxeTable
                :tablecode="'pro_outsourcing_delivery_fl'"
                :data="form.raws"
                :gridEvts="gridEvts"
                :gridOps="gridFloptions"
                ref="subbefl"
              >
              </sc-VxeTable>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-form>

    <!-- </sc-water-mark> -->
    <template #footer>
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
    </template>
  </el-dialog>
  <skBrowserChoose
    v-model="dialog.openChooseDlg"
    :name="'storage_browser'"
    @close="dialog.openChooseDlg = false"
    :params="{ 'material.category.material_nature_id': 3, type_id: 1 }"
    @select="additems"
  >
  </skBrowserChoose>
  <skBrowserChoose
    v-model="dialog.openChooseProDlg"
    :name="'storage_pro_browser'"
    @close="dialog.openChooseProDlg = false"
    @select="additems"
  >
  </skBrowserChoose>
  <skBrowserChoose
    v-model="dialog.openChooseFlDlg"
    :name="'storage_fl_browser'"
    @close="dialog.openChooseFlDlg = false"
    @select="addFlitems"
  >
  </skBrowserChoose>
  <pack
    v-if="dialog.pack"
    ref="pack"
    @success="packsucess"
    @closed="dialog.pack = false"
  ></pack>
</template>
<script>
import tool from "@/utils/tool";
import skAutoChoose from "@/components/skAutoChoose";
import skBrowserChoose from "@/components/skBrowserChoose";
import skDicSelect from "@/components/skDicSelect";
import pack from "./pack";
// import XEUtils from "xe-utils";
export default {
  emits: ["success", "closed"],
  components: { skAutoChoose, skBrowserChoose, skDicSelect, pack },
  data() {
    return {
      mode: "add",
      dialog: {
        pack: false,
        openChooseDlg: false,
        openChooseFlDlg: false,
        openChooseProDlg: false,
      },
      form: {
        billdate: tool.SYS_DATE(),
        quantity: 0,
        processes: [],
        price: 0,
        car: { company: {} },
        process_route: {},
        outfactory: {},
        details: [],
        raws: [],
      },
      gridFloptions: {
        height: 300,
        columns: [
          {
            field: "rate",
            event: {
              keyup: ({ row }) => {
                row["quantity"] = (row["rate"] * this.form.quantity) / 100;
              },
            },
          },
        ],
      },
      gridEvts: {
        chooseStorage: () => {
          this.dialog.openChooseFlDlg = true;
        },
      },

      gridEvtsyl: {
        chooseStorage: () => (this.dialog.openChooseDlg = true),
        choosePro: () => {
          this.dialog.openChooseProDlg = true;
        },
        edit: ({ button }) => {
          this.edit(button.selectRecords[0]);
        },
        cellDblclick: ({ row }) => {
          this.edit(row);
        },
      },
      gridSubOpts: {
        height: 300,
      },
      titleMap: {
        add: "新增",
        edit: "编辑",
      },
      rules: {
        outfactory_id: { required: true, message: "加工厂必填" },
        process_route_id: { required: true, message: "工艺必选" },
        billdate: { required: true, message: "单据日期必填" },
        price: { required: true, message: "外发单价必填" },
      },
      visible: false,
      isSaveing: false,
    };
  },
  watch: {
    "form.details": {
      handler() {
        this.form.quantity = this.form.details.reduce(
          (sum, v) => sum + parseFloat(v.quantity),
          0
        );
        this.computerAmount();
        this.cpomputerRaws();
      },
      deep: true,
    },

    "form.processes": {
      handler() {
        this.form.price = this.form.processes.reduce(
          (sum, v) => sum + parseFloat(v.process.out_product_price),
          0
        );
        this.computerAmount();
      },
      deep: true,
    },
  },
  mounted() {},
  methods: {
    edit(row) {
      this.dialog.pack = true;
      this.$nextTick(() => {
        let indexrow = this.form.details.find((vv) => vv.unkey.value == row.unkey.value);
        this.$refs.pack.setData(indexrow).open();
      });
    },
    open(mode = "add") {
      this.mode = mode;
      this.visible = true;
      return this;
    },
    cpomputerRaws() {
      this.form.raws = this.form.raws.map((row) => {
        row.quantity = (row.rate * this.form.quantity) / 100;
        return row;
      });
    },
    computerAmount() {
      this.form.amount = this.form.price * this.form.quantity;
    },
    selectCar(data) {
      if (typeof data.code == "undefined") {
        data = { company: {} };
        this.form.car_id = 0;
      }
      this.form.car = data;
    },
    setStorageData(row) {
      row["md_auxiliary_quantity"] = row["auxiliary_quantity"] = parseFloat(
        row["available_auxiliary_quantity"]
      );
      row["md_quantity"] = row["quantity"] = parseFloat(row["available_quantity"]);
      row.unkey = {
        value: row.location_id + row.batchno + row.material_id + row.type_id,
      };
      this.removeUnNeedField(row);
    },
    removeUnNeedField(row) {
      row.id = "row" + new Date().getTime();
      delete row.in_quantity;
      delete row.in_auxiliary_quantity;
      delete row.occupy_quantity;
      delete row.occupy_auxiliary_quantity;
      delete row.out_quantity;
      delete row.out_auxiliary_quantity;
      delete row.available_quantity;
      delete row.available_auxiliary_quantity;
      delete row.faultle_quantity;
      delete row.faultle_auxiliary_quantity;
      delete row.available_mquantity;
      delete row.available_auxiliary_mquantity;
    },
    setStorageProData(row) {
      row["md_auxiliary_quantity"] = row["auxiliary_quantity"] = parseFloat(
        row["faultle_auxiliary_quantity"] ?? 1
      );
      row["md_quantity"] = row["quantity"] = parseFloat(row["faultle_quantity"]);
      row.unkey = {
        value: row.location_id + row.batchno + row.material_id + row.type_id,
      };
      this.removeUnNeedField(row);
    },
    additems(items) {
      items.filter((row) => {
        if (this.dialog.openChooseDlg) this.setStorageData(row);
        else this.setStorageProData(row);
        let indexrow = this.form.details.find((vv) => vv.unkey.value == row.unkey.value);
        if (indexrow) {
          indexrow.packs.push(row);
          indexrow.quantity += parseFloat(row.quantity);
          indexrow.auxiliary_quantity += parseFloat(row.auxiliary_quantity);
        } else {
          row.packs = [this.$TOOL.objCopy(row)];
          this.form.details.push(row);
        }
      });
      this.dialog.openChooseProDlg = this.dialog.openChooseDlg = false;
    },
    addFlitems(items) {
      items.filter((row) => {
        row.rate = 100;
        row.quantity = (row.rate * this.form.quantity) / 100;
        row.id = "row" + new Date().getTime();
        this.form.raws.push(row);
      });
      this.dialog.openChooseFlDlg = false;
    },
    packsucess() {
      this.$refs.subbeyl.xGrid.updateFooter();
    },
    disabledDate(time) {
      return time.getTime() > Date.now();
    },

    //表单提交方法
    submit() {
      this.$refs.dialogForm.validate(async (valid) => {
        if (valid) {
          this.isSaveing = true;
          var res = await this.$API.pro.outsourcing.delivery.save.post(this.form);
          this.isSaveing = false;
          if (res.code == 200) {
            this.$emit("success", this.form);
            this.visible = false;
            this.$message.success("操作成功");
          }
        }
      });
    },
    async getInfo(code) {
      var res = await this.$API.pro.outsourcing.delivery.info.get({
        filter: [{ code: code }],
      });
      if (res.code == 200) {
        Object.assign(this.form, tool.objCopy(tool.removeNull(res.data)));
        this.form.details = res.data.details.map((v) => {
          v.unkey = {
            value: v.location_id + v.batchno + v.material_id + v.type_id,
          };
          return v;
        });
      }
    },

    //表单注入数据
    setData(data) {
      this.getInfo(data.code);
    },
  },
};
</script>

<style>
.attachments .el-upload--picture-card,
.attachments .el-upload-list--picture-card .el-upload-list__item {
  width: 100px;
  height: 100px;
  overflow: hidden;
}
</style>
